<script lang="ts" setup>
import { onMounted } from 'vue';
import { setTokenForClient, clearTokenForClient, setAtomGitUserForClient } from '@/common/utils/auth';
import { $fetch } from '@/passport/utils/fetch';

const props = defineProps({
  code: {
    type: String,
    default: '',
  },
  from: {
    type: String,
    default: '/',
  },
});

onMounted(async () => {
  // 检查 from 合法性，只支持站内地址
  if (!props.from.startsWith('/')) {
    window.location.href = '/';

    return;
  }

  const { isSuccess, data } = await $fetch('/user/accessToken', {
    data: {
      code: props.code,
    },
  });

  if (isSuccess) {
    setTokenForClient(data.access_token);

    if (!import.meta.env.DEV) {
      // 同步登录到 AtomGit
      setAtomGitUserForClient(data.user || {});

      // 这里是用于种 AtomGit 登录所需的 Cookie
      // 因为 AtomGit 的登录 Cookie 必须是 httpOnly 的所以需要由服务器种
      await $fetch('/passport/index/transform-atomgit-token', {
        method: 'post',
        baseURL: '/',
        data: {
          accessToken: data.access_token,
          expiresAt: data.expires_at,
          expiresIn: data.expires_in,
          idToken: data.id_token,
          refreshToken: data.refresh_token,
        },
      });
    }

    location.href = props.from;
  }
  else {
    clearTokenForClient();
    location.href = '/';
  }
});
</script>

<template>
  <main>
    正在登录，请稍候...
  </main>
</template>
